from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.views import APIView
from demo2 import main_serializers,models
from rest_framework.response import  Response
# Create your views here.


class Add(APIView):
    def post(self,request):
        ser=main_serializers.MainSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code":200})
        return Response({"code": 400})



from django.core.files.storage import default_storage
class Uploads(APIView):
    def post(self,request):
        file=request.data.get('file')
        type=['jpg','png']
        if file.name.split('.')[-1] not in type:
            return Response({'code':401,"msg":'图片类型不符合要求'})

        if file.size>1024*1024*4:
            return Response({'code':401,"msg":'图片大小不符合要求'})
        uploadsfile=default_storage.save('/img',file.name,file)
        url=default_storage.url(uploadsfile)
        return Response({'url':url})

class Mainlist(ListAPIView):
    queryset = models.MainMode.objects.all()
    serializer_class = main_serializers.MainSer



class Select(APIView):
     def get(self,request):
         id=request.query_params.get('id')
         info=models.MainMode.objects.filter(id=id).first()
         ser=main_serializers.MainSer(info)
         return Response({"code":200,'data':ser.data})




